package com.iot.core.domain;

import java.util.ArrayList;
import java.util.List;

public class BuildTree {

	public static <T> List<MenuTree<T>> buildMenuTree(List<MenuTree<T>> nodes) {
		if (nodes == null) {
			return null;
		}
		List<MenuTree<T>> topNodes = new ArrayList<MenuTree<T>>();
		for (MenuTree<T> children : nodes) {
			String pid = children.getParentId();
			if (pid == null || "0".equals(pid)) {
				topNodes.add(children);
				continue;
			}
			for (MenuTree<T> parent : nodes) {
				String id = parent.getMenuId();
				if (id != null && id.equals(pid)) {
					parent.getChildren().add(children);
					children.setHasParent(true);
					parent.setHasChildren(true);
					continue;
				}
			}
		}
		return topNodes;
	}

    /**
     * 构建机构用户树
     * @param nodes 全部节点
     * @param topNode 站点机构节点
     * @param <T>
     * @return
     */
    public static <T> List<OrgTree<T>> buildOrgTree(List<OrgTree<T>> nodes,OrgTree<T> topNode) {
        if (nodes == null) {
            return null;
        }
        List<OrgTree<T>> topNodes = new ArrayList<>();

        List<OrgTree<T>> topNodeChildren = new ArrayList<>();
        for (OrgTree<T> children : nodes) {
            String pid = children.getParentId();
            if (pid == null || "0".equals(pid)) {
                children.setHasParent(true);
                children.setParentId(topNode.getId());
                topNodeChildren.add(children);
                topNode.setHasChildren(true);
                continue;
            }
            for (OrgTree<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    parent.getChildren().add(children);
                    children.setHasParent(true);
                    parent.setHasChildren(true);
                    continue;
                }
            }
        }

        topNode.setChildren(topNodeChildren);
        topNode.setHasParent(false);
        topNodes.add(topNode);
        return topNodes;
    }

}
